package com.wn.demo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import util.MapUtils;

public class Test {
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	public static void main(String[] args) {
		try {
			testSign();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void testSign() throws Exception{
		String pid = "YGFinancial";
		String type = "JD";
		String pwd = "71181494f321b7f511fd18c8dd516267";
		Map<String,String> params=new HashMap<String, String>();
		params.put("pid", pid);
		params.put("type", type);
		params.put("pwd", pwd);
		Map<String,String> sortMap=MapUtils.sortMapByKey(params);
		String signStr = getSignStr(sortMap);
		System.out.println("待签名串："+signStr);
		String sign=md5(signStr);
		System.out.println("签名串："+sign);
	}
	
	private static String getSignStr(Map<String, String> map) throws UnsupportedEncodingException {
		String md5 = "";
		Set<String> keys = map.keySet();
		for (String key : keys) {
			String value = map.get(key);
			if (key != null)
				md5 += key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
			else
				md5 += key + "=&";

		}
		md5 = md5.substring(0, md5.length() - 1);
		return md5;
	}
	
	private static String md5(String message){  
        return encode("MD5",message);  
    }  

	private static String encode(String code,String message){  
	    MessageDigest md;  
	    String encode = null;  
	    try {  
	        md = MessageDigest.getInstance(code);  
	        encode = byteArrayToHexString(md.digest(message  
	                .getBytes()));  
	    } catch (NoSuchAlgorithmException e) {  
	        e.printStackTrace();  
	    }  
	    return encode;  
	} 
	
	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();

		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}
	
	private static String byteToHexString(byte b) {
		int n = b;

		if (n < 0) {
			n = 256 + n;
		}

		int d1 = n / 16;
		int d2 = n % 16;

		return hexDigits[d1] + hexDigits[d2];
	}
}
